import logging

from poker_bot.core.models.dto.account import AccountDTO
from poker_bot.core.models.enums.account import AccountStatus
from poker_bot.database.uow import SQLAlchemyUoW
from poker_bot.domain.account import AccountEntity
from poker_bot.domain.user import UserEntity

logger = logging.getLogger(__name__)


class AccountService:
    def __init__(self, uow: SQLAlchemyUoW):
        self._uow = uow

    async def get_account_by_id(self, account_id: int) -> AccountDTO | None:
        """Получаем аккаунт по id"""

        return await self._uow.account_reader.get_account_by_id(account_id)

    async def get_user_accounts(self, user_tg_id: int) -> list[AccountDTO]:
        """Получаем аккаунты пользователя"""

        return await self._uow.account_reader.get_user_accounts(user_tg_id)

    async def get_accounts_for_confirmation(
        self,
    ) -> list[AccountDTO]:
        """Получаем аккаунты для подтверждения"""

        return await self._uow.account_reader.get_accounts_for_confirmation()

    async def update_account_status(
        self, account_id: int, status: AccountStatus
    ) -> None:
        account: AccountEntity = await self._uow.account_repo.acquire_account_by_id(
            account_id
        )
        account.update_status(status)

        await self._uow.account_repo.update_account(account)

        await self._uow.commit()

    async def create_account(self, user_tg_id: int, account_id: int) -> AccountEntity:
        """Создаем аккаунт пользователя"""

        user: UserEntity = await self._uow.user_repo.acquire_user_by_tg_id(user_tg_id)
        account = AccountEntity.create(user_id=user.id, account_id=account_id)
        try:
            account = await self._uow.user_repo.create_user_account(account)
        except Exception as err:
            await self._uow.rollback()
            raise err

        await self._uow.commit()

        return account
